package studysystem.demo.controller;

import com.github.pagehelper.PageHelper;
import org.apache.shiro.codec.Hex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import studysystem.demo.bean.Manager;
import studysystem.demo.bean.Learner;
import studysystem.demo.bean.Role;
import studysystem.demo.mapper.LearnerMapper;
import studysystem.demo.mapper.ManagerMapper;
import studysystem.demo.tool.Mess;
import studysystem.demo.tool.MyResp;

import javax.servlet.http.HttpServletRequest;
import java.security.MessageDigest;
import java.sql.Timestamp;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Controller
public class ManagerController {

    @Autowired
    private ManagerMapper managerMapper;
    @Autowired
    private LearnerMapper learnerMapper;

    //查询所有管理员 兼 搜索 兼 分页
    @CrossOrigin
    @RequestMapping(value="/admin/all", method = RequestMethod.GET)
    @ResponseBody
    public MyResp adminList(@RequestParam("pageIndex") Integer pageIndex,
                              @RequestParam("pageSize") Integer pageSize,
                              @RequestParam(value="value",required = false,defaultValue = "null") String value,
                              @RequestParam(value="type",required = false,defaultValue = "null") String type){
        if(pageIndex==null){
            pageIndex=1;
        }
        if(pageSize==null){
            pageSize=10;
        }
        PageHelper.startPage(pageIndex, pageSize);
        switch (type){
            case "Name":
                return  MyResp.render(0,"获取成功", managerMapper.findAdminByName(value), managerMapper.findAdminCountByName(value));
            case "jobnum":
                return MyResp.render(0,"获取成功", managerMapper.findAdminByJobnum(value), managerMapper.findAdminCountByJobnum(value));
            case "":
                return MyResp.render(0,"获取成功", managerMapper.findAdminAll(), managerMapper.findAdminCountAll());
            default:
                return MyResp.render(0,"获取成功", managerMapper.findAdminAll(), managerMapper.findAdminCountAll());
        }
    }

    //新建管理员  测试OK
    @CrossOrigin
    @RequestMapping(value = "/admin/new",method = RequestMethod.POST)
    @ResponseBody
    public Mess addAdmin(@RequestBody Manager adminEntity){
        String b;
        if(adminEntity.getJobnum()==null||!chickJobnum(adminEntity.getJobnum())){
            b = "工号格式错误";
        }else if (managerMapper.findAdminInfo(adminEntity.getJobnum())!=null){
            b = "此工号已注册";
        }else if (adminEntity.getPassword()==null||!chickPassword(adminEntity.getPassword())) {
            b = "密码格式错误";
        }else if (adminEntity.getPassword2()==null||!adminEntity.getPassword().equals(adminEntity.getPassword2())) {
            b = "两次输入的密码不一致！";
        }else if (adminEntity.getName()==null||!chickName(adminEntity.getName())){
            b = "姓名格式错误";
        }else if (adminEntity.getPhone()==null||!chickPhone(adminEntity.getPhone())){
            b = "手机号码错误";
        } else if (adminEntity.getSex()==null||!chickSex(adminEntity.getSex())){
            b = "性别填写错误";
        }else if (adminEntity.getUserid()==null||!chickUserid(adminEntity.getUserid())){
            b = "身份证格式错误";
        }else {
            String salt = adminEntity.getJobnum();
            adminEntity.setPassword(md5Hex(salt+adminEntity.getPassword()));
            managerMapper.saveAdmin(adminEntity);
           /**
            Role roleEntity = new Role();
            roleEntity.setUsername(adminEntity.getJobnum());
            roleEntity.setRole("2"); //--管理员
            managerMapper.saveRole(roleEntity);
            **/
            b = "注册成功";
        }
        return Mess.info(b);
    }

    //删除管理员
    @CrossOrigin
    @RequestMapping(value = "/admin/delete/{jobnum}", method = RequestMethod.DELETE)
    @ResponseBody
    public Mess deleteAdmin(@PathVariable String jobnum){
        String b;
        if(jobnum!=null&& managerMapper.findAdminInfo(jobnum)!=null&&chickJobnum(jobnum)){
            managerMapper.deleteAdmin(jobnum);
            //managerMapper.deleteRole(jobnum);
            b = "删除成功!";
        }else {
            b = "删除失败!";
        }
        return Mess.info(b);
    }

    //修改个人信息  测试OK
    @CrossOrigin
    @RequestMapping(value = "/admin/update",method = RequestMethod.PUT)
    @ResponseBody
    public Mess updateAdmin(@RequestBody Manager adminEntity, HttpServletRequest request){
        String b;
        Manager admin =(Manager) request.getSession().getAttribute("user");
        adminEntity.setJobnum(admin.getJobnum());
        if (adminEntity.getName()==null||!chickName(adminEntity.getName())){
            b = "姓名格式错误";
        }else if (adminEntity.getPhone()==null||!chickPhone(adminEntity.getPhone())) {
            b = "手机号码填写错误";
        }else if (adminEntity.getSex()==null||!chickSex(adminEntity.getSex())){
            b = "性别填写错误";
        }else if (adminEntity.getUserid()==null||!chickUserid(adminEntity.getUserid())){
            b = "身份证格式错误";
        }else {
            String salt = adminEntity.getPhone();
            adminEntity.setPassword(md5Hex(salt+adminEntity.getPassword()));
            managerMapper.updateAdmin(adminEntity);
            b = "修改成功!";
        }
        return Mess.info(b);
    }

    //查看个人信息 测试OK
    @CrossOrigin
    @RequestMapping(value = "/admin/info",method = RequestMethod.GET)
    @ResponseBody
    public Manager personalInfo(HttpServletRequest request){
        Manager admin =(Manager) request.getSession().getAttribute("user");
        return managerMapper.findAdminInfo(admin.getJobnum());
    }

    //修改密码   测试OK
    @CrossOrigin
    @RequestMapping(value = "/admin/updatepsd",method = RequestMethod.PUT)
    @ResponseBody
    public Mess updatePsd(@RequestBody Manager adminEntity, HttpServletRequest request){
        String b;
        Manager admin =(Manager) request.getSession().getAttribute("user");
        adminEntity.setJobnum(admin.getJobnum());
        if (adminEntity.getPassword()==null||!chickPassword(adminEntity.getPassword())) {
            b = "密码格式错误!";
        }else if(adminEntity.getOldpassword()==null||!md5Hex(adminEntity.getJobnum()+adminEntity.getOldpassword()).equals(managerMapper.findAdminPsw(adminEntity.getJobnum()).getPassword())){
            b = "旧密码错误!";
        }else {
            adminEntity.setPassword(md5Hex(adminEntity.getJobnum()+adminEntity.getPassword()));
            managerMapper.updatePsw(adminEntity);
            b = "密码修改成功!";
        }
        return Mess.info(b);
    }
    //修改学习者个人信息 测试OK
    @CrossOrigin
    @RequestMapping(value = "/learner/update/{phone}",method = RequestMethod.PUT)
    @ResponseBody
    public Mess updateLearner(@PathVariable String phone,@RequestBody Learner learnerEntity, HttpServletRequest request){
        String b;
        learnerEntity.setPhone(phone);
        if (learnerEntity.getName()==null||!chickName(learnerEntity.getName())){
            b = "姓名格式错误!";
        }else if (learnerEntity.getSex()==null||!chickSex(learnerEntity.getSex())){
            b = "性别填写错误!";
        }else if (learnerEntity.getUserid()==null||!chickUserid(learnerEntity.getUserid())){
            b = "身份证格式错误!";
        }else {
            learnerMapper.updateLearner(learnerEntity);
            b = "修改成功!";
        }
        return Mess.info

                (b);
    }


    /**
     * 方法
     * @param src
     * @return
     */

    //加盐密码哈希
    private static String md5Hex(String src) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] bs = md5.digest(src.getBytes());
            new Hex();
            return new String(Hex.encode(bs));
        } catch (Exception e) {
            return null;
        }
    }

    //检验手机号
    private boolean chickPhone(String username){
        Pattern pattern = Pattern.compile("^1[345789]\\d{9}$");
        Matcher match=pattern.matcher(username);
        return match.matches();
    }

    //检验工号
    private boolean chickJobnum(String username){
        Pattern pattern = Pattern.compile("^\\d{10}$");
        Matcher match=pattern.matcher(username);
        return match.matches();
    }

    //检验密码
    private boolean chickPassword(String password){
        Pattern pattern = Pattern.compile("^[a-zA-Z0-9]{6,15}$");
        Matcher match=pattern.matcher(password);
        return match.matches();
    }

    //检验性别
    private boolean chickSex(String sex){
        Boolean b = false;
        if(sex.equals("男")||sex.equals("女")){
            b = true;
        }
        return b;
    }

    //检验身份证
    private boolean chickUserid(String userid){
        Pattern pattern = Pattern.compile("^[1-9][0-9]{5}(19|20)[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|30|31)|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}([0-9]|X)$");
        Matcher match=pattern.matcher(userid);
        return match.matches();
    }

    //检验姓名
    private boolean chickName(String name){
        Pattern pattern = Pattern.compile("^[\u4e00-\u9fa5]{2,5}$");
        Matcher match=pattern.matcher(name);
        return match.matches();
    }

    //获取当前时间
    private Date getNtime(){
        Date date = new Date();
        return new Timestamp(date.getTime());
    }

}
